#!/bin/sh
# Copyright © 2005-2012  Roger Leigh <rleigh@codelibre.net>
#
# schroot is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# schroot is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see
# <http://www.gnu.org/licenses/>.
#
#####################################################################

# This script is an example of how to use the "custom" chroot type.
# This simple example replicates some of the functionality of the
# "directory" chroot type, using the "custom.dir" setting in place
# of the "directory" setting, which sets CUSTOM_DIR in the script
# environment.  Here, we bind mount it as would normally happen for
# the directory type.
#
# Note that this replicates some of the 10mount logic, and does not
# handle recovery, so is not completely robust.  This will require
# reworking or splitting of 10mount into separate pieces in order
# to handle custom types without working the logic for the custom
# types into 10mount directly (currently the recommended course of
# action).

set -e

. "$SETUP_DATA_DIR/common-data"
. "$SETUP_DATA_DIR/common-functions"
. "$SETUP_DATA_DIR/common-config"

# Mount a filesystem
# $1: mount options
# $2: mount device
# $3: mount location
do_mount()
{
    info "Mounting $2 on $3"

    if [ ! -d "$3" ]; then
        mkdir -p "$3"
    fi
    if [ ! -d "$3" ]; then
        fatal "$3 does not exist, and could not be created"
    fi

    info "$MOUNT_VERBOSE $1 $2 $3"
    mount $MOUNT_VERBOSE $1 "$2" "$3"
}

if [ "$CHROOT_TYPE" = "custom" ] && [ -n "$CUSTOM_DIR" ]; then

    if [ $STAGE = "setup-start" ]; then

        info "CUSTOM SETUP using $CUSTOM_DIR"

        case "$(uname -s)" in
            *FreeBSD) :
                BINDOPT="-t nullfs"
                ;;
            *):
                BINDOPT="--bind"
                ;;
        esac

        CHROOT_MOUNT_OPTIONS="$BINDOPT $CHROOT_MOUNT_OPTIONS"
        CHROOT_MOUNT_DEVICE="$CUSTOM_DIR"

        if [ ! -d "$CUSTOM_DIR" ]; then
            fatal "Directory '$CUSTOM_DIR' does not exist"
        fi

        if [ ! -d "$CHROOT_MOUNT_LOCATION" ]; then
            mkdir -p "$CHROOT_MOUNT_LOCATION"
        fi
        if [ ! -d "$CHROOT_MOUNT_LOCATION" ]; then
            fatal "$CHROOT_MOUNT_LOCATION does not exist, and could not be created"
        fi

        do_mount "$CHROOT_MOUNT_OPTIONS" "$CHROOT_MOUNT_DEVICE" "$CHROOT_MOUNT_LOCATION"

    fi

fi

